package com.norra.client.ui

import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.view.Window
import android.view.WindowManager
import androidx.core.app.ActivityCompat
import com.norra.client.App
import com.norra.client.R

class SplashActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        //全屏
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN)
        setContentView(R.layout.activity_splash)
        val permissionResult = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)

        if (permissionResult == PackageManager.PERMISSION_GRANTED) {
            go()
        } else {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 123)
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 123 && permissions.contains(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                go()
            } else {
                showNeedPermissionDialog()
            }
        }
    }

    private fun showNeedPermissionDialog() {
        val dialog = AlertDialog.Builder(this)
                .setCancelable(false)
                .create()
        dialog.show()
        val window = dialog.window!!
        window.setContentView(R.layout.dialog_permission);
        window.findViewById<View>(R.id.btn_no).setOnClickListener {
            quit()
        }

        window.findViewById<View>(R.id.btn_yes).setOnClickListener {
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            val uri = Uri.fromParts("package", packageName, null);
            intent.data = uri;
            startActivity(intent)
            finish()
        }
    }

    private fun quit() {
        finish()
    }

    private fun go() {
        App.get().mainHandler.postDelayed({
            if (App.get().isLogin()) {
                startActivity(MainActivity::class.java)
            } else {
                startActivity(LoginActivity::class.java)
            }
            finish()
        }, 1000)
    }
}